package com.lytis.zoovideo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lytis.zoovideo.common.R;
import com.lytis.zoovideo.entity.User;
import com.lytis.zoovideo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :DongPeiLei
 * @description :
 * @create :2022-05-30 16:32:00
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping
    public R login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User usernameRes = userService.getOne(queryWrapper);
        if (usernameRes == null) {
            return R.error().message("账户不存在，请注册后再登录!");
        }
        queryWrapper.eq("password", password);
        User passwordRes = userService.getOne(queryWrapper);
        if (passwordRes == null) {
            return R.error().message("密码错误，请重新输入!");
        } else {

            return R.ok().data("username", passwordRes.getUsername()).data("userId", passwordRes.getId()).message("登录成功");
        }
    }

    @PostMapping
    public R register(@RequestBody User user) {
        String username = user.getUsername();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User queryResult = userService.getOne(queryWrapper);
        if (queryResult != null) {
            return R.error().message("账号已存在,请直接登录");
        } else {
            boolean save = userService.save(user);
            return save ? R.ok().message("注册成功") : R.error().message("注册失败");
        }
    }
}
